package com.zuoshenge.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;


@Component
public class CaffeineCacheUtil {
    LoadingCache<String, Object> cache = Caffeine.newBuilder()
            // 初始容量
            .initialCapacity(300)
            // 最大存储容量
            .maximumSize(5000)
            // .expireAfterWrite(10, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Object>() {
                @Override
                public Object load(@NonNull String s) {
                    return "从数据库读取";
                }

                @Override
                public @NonNull Map<@NonNull String, @NonNull Object> loadAll(@NonNull Iterable<? extends @NonNull String> keys) {
                    return null;
                }
            });

    public void set(String key, Object value) {
        cache.put(key, value);
    }

    public Object getIfPresent(String key) {
        return cache.getIfPresent(key);
    }

    // 从缓存中找，如果找不到就从自定义的函数去找
    public Object get(String key, Function<Object, Map<String, Object>> function) {
        if (function != null) {
            // 如果function不为空，则尝试使用它来获取值
            return function.apply(key);
        } else {
            // 如果function为空，则让Caffeine使用CacheLoader的load方法
            return cache.get(key);
        }
    }
}
